import React, { useEffect, useMemo, useRef, useState } from 'react'
import {
  Settings,
  Globe,
  Image as ImageIcon,
  Save,
  RefreshCw,
  Languages,
  Phone,
  MessageCircle,
  Mail,
  CreditCard,
  ShieldCheck,
  Store,
  Network,
  Plug,
  ServerCog,
  Database,
  Clock,
  Boxes,
  Rocket,
  CheckCircle,
  Plus,
  Trash2,
  Truck,
} from 'lucide-react'
import { Button, Card, Input } from '@/components'
import { useTranslation, Language } from '@/utils/i18n'
import { useSystemSettingsStore, SystemSettings as SystemSettingsType } from '@/stores/systemSettingsStore'

const SystemSettings: React.FC = () => {
  const { t, locale, setLocale } = useTranslation()
  const { settings: storedSettings, updateSettings, resetSettings } = useSystemSettingsStore()
  const [settings, setSettings] = useState<SystemSettingsType>(storedSettings)
  const [activeTab, setActiveTab] = useState('branding')
  const [loading, setLoading] = useState(false)
  const [saveSuccess, setSaveSuccess] = useState(false)
  const logoInputRef = useRef<HTMLInputElement>(null)

  const resolveLocale = (value: string): Language => (value === 'en-US' ? 'en-US' : 'zh-CN')

  useEffect(() => {
    setSettings(storedSettings)
  }, [storedSettings])

  useEffect(() => {
    setSettings((prev) => ({
      ...prev,
      branding: {
        ...prev.branding,
        defaultLanguage: locale,
      },
    }))
  }, [locale])

  const tabs = useMemo(
    () => [
      { id: 'branding', label: '基础信息与对外展示', icon: Settings },
      { id: 'business', label: '业务功能精细化配置', icon: Rocket },
      { id: 'permissions', label: '权限与角色管理', icon: ShieldCheck },
      { id: 'integrations', label: '系统集成与外部对接', icon: Plug },
      { id: 'technical', label: '技术级配置（运维）', icon: ServerCog },
    ],
    []
  )

  const handleSave = async () => {
    setLoading(true)
    setSaveSuccess(false)
    updateSettings(settings)
    await new Promise((resolve) => setTimeout(resolve, 800))
    setLoading(false)
    setSaveSuccess(true)
    setTimeout(() => setSaveSuccess(false), 3000)
  }

  const handleReset = () => {
    resetSettings()
  }

  const handleBrandingChange = <K extends keyof SystemSettingsType['branding']>(key: K, value: SystemSettingsType['branding'][K]) => {
    setSettings((prev) => {
      const nextBranding = {
        ...prev.branding,
        [key]: value,
      }

      if (key === 'platformNameZh' && typeof value === 'string') {
        nextBranding.platformName = value
      }

      if (key === 'platformName' && typeof value === 'string') {
        if (!nextBranding.platformNameZh) {
          nextBranding.platformNameZh = value
        }
      }

      return {
        ...prev,
        branding: nextBranding,
      }
    })
    if (key === 'defaultLanguage') {
      setLocale(resolveLocale(String(value)))
    }
  }

  const handlePaymentToggle = (channel: keyof SystemSettingsType['business']['transaction']['paymentChannels']) => {
    setSettings((prev) => ({
      ...prev,
      business: {
        ...prev.business,
        transaction: {
          ...prev.business.transaction,
          paymentChannels: {
            ...prev.business.transaction.paymentChannels,
            [channel]: !prev.business.transaction.paymentChannels[channel],
          },
        },
      },
    }))
  }

  const handleCategoryAdd = () => {
    const next = prompt('请输入要新增的类目（示例：智能家居-智能门锁）')
    if (!next) return
    setSettings((prev) => ({
      ...prev,
      business: {
        ...prev.business,
        product: {
          ...prev.business.product,
          customCategories: Array.from(new Set([...prev.business.product.customCategories, next])),
        },
      },
    }))
  }

  const handleCategoryRemove = (category: string) => {
    setSettings((prev) => ({
      ...prev,
      business: {
        ...prev.business,
        product: {
          ...prev.business.product,
          customCategories: prev.business.product.customCategories.filter((item) => item !== category),
        },
      },
    }))
  }

  const handleMembershipChange = (index: number, key: 'name' | 'threshold' | 'perks', value: string) => {
    setSettings((prev) => {
      const copy = [...prev.business.marketing.membershipLevels]
      if (key === 'threshold') {
        copy[index] = { ...copy[index], threshold: Number(value) || 0 }
      } else {
        copy[index] = { ...copy[index], [key]: value }
      }
      return {
        ...prev,
        business: {
          ...prev.business,
          marketing: {
            ...prev.business.marketing,
            membershipLevels: copy,
          },
        },
      }
    })
  }

  const handleAddMembership = () => {
    setSettings((prev) => ({
      ...prev,
      business: {
        ...prev.business,
        marketing: {
          ...prev.business.marketing,
          membershipLevels: [
            ...prev.business.marketing.membershipLevels,
            {
              id: `vip-${Date.now()}`,
              name: '新会员等级',
              threshold: 0,
              perks: '自定义权益描述',
            },
          ],
        },
      },
    }))
  }

  const handleRemoveMembership = (id: string) => {
    setSettings((prev) => ({
      ...prev,
      business: {
        ...prev.business,
        marketing: {
          ...prev.business.marketing,
          membershipLevels: prev.business.marketing.membershipLevels.filter((item) => item.id !== id),
        },
      },
    }))
  }

  const handleRoleToggle = (roleKey: string, permission: string) => {
    setSettings((prev) => ({
      ...prev,
      permissions: {
        ...prev.permissions,
        roles: prev.permissions.roles.map((role) =>
          role.key === roleKey
            ? {
                ...role,
                permissions: role.permissions.includes(permission)
                  ? role.permissions.filter((item) => item !== permission)
                  : [...role.permissions, permission],
              }
            : role
        ),
      },
    }))
  }

  const handleOAuthChange = (provider: 'wechat' | 'qq' | 'alipay', field: 'appId' | 'appSecret' | 'callback', value: string) => {
    setSettings((prev) => ({
      ...prev,
      integrations: {
        ...prev.integrations,
        oauthProviders: {
          ...prev.integrations.oauthProviders,
          [provider]: {
            ...prev.integrations.oauthProviders[provider],
            [field]: value,
          },
        },
      },
    }))
  }

  const handleLogisticsToggle = (provider: string) => {
    setSettings((prev) => ({
      ...prev,
      integrations: {
        ...prev.integrations,
        logistics: prev.integrations.logistics.map((item) =>
          item.provider === provider ? { ...item, enabled: !item.enabled } : item
        ),
      },
    }))
  }

  const renderBrandingTab = () => (
    <div className="space-y-6">
      <Card>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <Input
                label="平台名称（中文）"
                value={settings.branding.platformNameZh ?? settings.branding.platformName}
                onChange={(e) => handleBrandingChange('platformNameZh', e.target.value)}
                placeholder="例如：电商后台管理系统"
                leftIcon={<Globe size={18} />}
              />
              <Input
                label="Platform Name (English)"
                value={settings.branding.platformNameEn ?? ''}
                onChange={(e) => handleBrandingChange('platformNameEn', e.target.value)}
                placeholder="e.g. E-commerce Admin Console"
                leftIcon={<Globe size={18} />}
              />
          <Input
            label="品牌口号 / 描述"
            value={settings.branding.slogan}
            onChange={(e) => handleBrandingChange('slogan', e.target.value)}
            placeholder="为全球商家提供敏捷运营体系"
          />
          <Input
            label="版权声明"
            value={settings.branding.copyright}
            onChange={(e) => handleBrandingChange('copyright', e.target.value)}
          />
          <Input
            label="备案号"
            value={settings.branding.icpNumber}
            onChange={(e) => handleBrandingChange('icpNumber', e.target.value)}
              />
              <div>
            <label className="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2 flex items-center gap-2">
              <Languages size={18} /> 多语言配置
            </label>
            <div className="space-y-2">
              <label className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-300">
                <input
                  type="checkbox"
                  checked={settings.branding.enableMultiLanguage}
                  onChange={(e) => handleBrandingChange('enableMultiLanguage', e.target.checked)}
                />
                启用多语言/多时区切换
                </label>
                <select
                value={resolveLocale(settings.branding.defaultLanguage)}
                onChange={(e) => handleBrandingChange('defaultLanguage', resolveLocale(e.target.value))}
                className="w-full px-3 py-2 border rounded-xl"
              >
                {[...new Set([...settings.branding.supportedLanguages, 'zh-CN', 'en-US'])]
                  .filter((lang): lang is Language => lang === 'zh-CN' || lang === 'en-US')
                  .map((lang) => (
                    <option key={lang} value={lang}>
                      {lang}
                    </option>
                  ))}
                </select>
              <Input
                label="支持语言列表"
                value={settings.branding.supportedLanguages.join(', ')}
                onChange={(e) =>
                  handleBrandingChange(
                    'supportedLanguages',
                    e.target.value
                      .split(',')
                      .map((item) => item.trim())
                      .filter(Boolean)
                  )
                }
                placeholder="例如：zh-CN, en-US"
              />
              </div>
          </div>
          <div>
            <label className="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2 flex items-center gap-2">
              <Clock size={18} /> 时区配置
            </label>
            <div className="space-y-2">
              <label className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-300">
                <input
                  type="checkbox"
                  checked={settings.branding.enableMultiTimezone}
                  onChange={(e) => handleBrandingChange('enableMultiTimezone', e.target.checked)}
                />
                针对跨境业务启用多时区
              </label>
              <Input
                label="默认时区"
                value={settings.branding.timezone}
                onChange={(e) => handleBrandingChange('timezone', e.target.value)}
                placeholder="Asia/Shanghai"
              />
                <Input
                label="支持时区列表"
                value={settings.branding.supportedTimezones.join(', ')}
                onChange={(e) =>
                  handleBrandingChange(
                    'supportedTimezones',
                    e.target.value
                      .split(',')
                      .map((item) => item.trim())
                      .filter(Boolean)
                  )
                }
                />
              </div>
          </div>
        </div>
      </Card>

      <Card>
        <div className="flex flex-col md:flex-row gap-6">
          <div className="flex-1 space-y-4">
            <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300">客服通道</h4>
            <Input
              label="客服热线"
              value={settings.branding.customerServicePhone}
              onChange={(e) => handleBrandingChange('customerServicePhone', e.target.value)}
              leftIcon={<Phone size={18} />}
            />
            <Input
              label="在线IM入口"
              value={settings.branding.customerServiceIM}
              onChange={(e) => handleBrandingChange('customerServiceIM', e.target.value)}
              leftIcon={<MessageCircle size={18} />}
            />
            <Input
              label="客服邮箱"
              value={settings.branding.customerServiceEmail}
              onChange={(e) => handleBrandingChange('customerServiceEmail', e.target.value)}
              leftIcon={<Mail size={18} />}
            />
          </div>
          <div className="md:w-64">
            <label className="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2 flex items-center gap-2">
              <ImageIcon size={18} /> 平台 Logo
                </label>
            <div
              className="w-56 h-56 rounded-xl border-2 border-dashed border-gray-300 dark:border-gray-600 flex items-center justify-center bg-gray-50 dark:bg-gray-800 cursor-pointer hover:border-blue-400"
              onClick={() => logoInputRef.current?.click()}
            >
              {settings.branding.platformLogo ? (
                <img src={settings.branding.platformLogo} alt="logo" className="w-full h-full object-contain p-2" />
              ) : (
                <span className="text-gray-400 text-sm">点击上传 Logo</span>
              )}
            </div>
                  <input
              ref={logoInputRef}
                    type="file"
              accept="image/png,image/jpeg"
                    className="hidden"
              onChange={(event) => {
                const file = event.target.files?.[0]
                if (!file) return
                if (!/^image\/(png|jpeg)$/.test(file.type)) {
                  alert('请上传 PNG / JPG 格式图片')
                          return
                        }
                        if (file.size > 2 * 1024 * 1024) {
                  alert('Logo 不可超过 2MB')
                          return
                        }
                        const reader = new FileReader()
                        reader.onload = (e) => {
                  handleBrandingChange('platformLogo', (e.target?.result as string) || '')
                        }
                        reader.readAsDataURL(file)
              }}
            />
            {settings.branding.platformLogo && (
              <Button
                variant="outline"
                size="sm"
                className="mt-3"
                onClick={() => handleBrandingChange('platformLogo', '')}
              >
                清除 Logo
              </Button>
            )}
                        </div>
                      </div>
      </Card>
                  </div>
  )

  const renderBusinessTab = () => (
    <div className="space-y-6">
      <Card>
        <h3 className="text-base font-semibold flex items-center gap-2 mb-4"><CreditCard size={18} /> 交易域</h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <p className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">支付方式开关</p>
            <div className="grid grid-cols-2 gap-3">
              {(
                [
                  { key: 'alipay', label: '支付宝' },
                  { key: 'wechat', label: '微信支付' },
                  { key: 'bank', label: '银联/银行卡' },
                  { key: 'cod', label: '货到付款' },
                ] as Array<{ key: keyof SystemSettingsType['business']['transaction']['paymentChannels']; label: string }>
              ).map((item) => (
                <label key={item.key} className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-300">
                  <input
                    type="checkbox"
                    checked={settings.business.transaction.paymentChannels[item.key]}
                    onChange={() => handlePaymentToggle(item.key)}
                  />
                  {item.label}
                </label>
              ))}
            </div>
          </div>
          <div className="space-y-4">
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300">提现规则</label>
            <select
              value={settings.business.transaction.withdrawalCycle}
              onChange={(e) =>
                setSettings((prev) => ({
                  ...prev,
                  business: {
                    ...prev.business,
                    transaction: {
                      ...prev.business.transaction,
                      withdrawalCycle: e.target.value as 'T+1' | 'T+3' | 'T+7',
                    },
                  },
                }))
              }
              className="w-full px-3 py-2 border rounded-xl"
            >
              <option value="T+1">T+1（快速到账）</option>
              <option value="T+3">T+3（平衡效率与风控）</option>
              <option value="T+7">T+7（大额资金）</option>
            </select>
            <Input
              label="手续费比例（%）"
              type="number"
              value={settings.business.transaction.withdrawalFeeRate}
              onChange={(e) =>
                setSettings((prev) => ({
                  ...prev,
                  business: {
                    ...prev.business,
                    transaction: {
                      ...prev.business.transaction,
                      withdrawalFeeRate: Number(e.target.value) || 0,
                    },
                  },
                }))
              }
            />
            <label className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-300">
              <input
                type="checkbox"
                checked={settings.business.transaction.couponStackable}
                onChange={(e) =>
                  setSettings((prev) => ({
                    ...prev,
                    business: {
                      ...prev.business,
                      transaction: {
                        ...prev.business.transaction,
                        couponStackable: e.target.checked,
                      },
                    },
                  }))
                }
              />
              优惠券可与平台满减叠加
            </label>
          </div>
        </div>
      </Card>

      <Card>
        <h3 className="text-base font-semibold flex items-center gap-2 mb-4"><Boxes size={18} /> 商品域</h3>
        <div className="space-y-4">
          <div>
            <div className="flex items-center justify-between mb-3">
              <p className="text-sm font-medium text-gray-700 dark:text-gray-300">自定义一级类目</p>
              <Button variant="outline" size="sm" onClick={handleCategoryAdd}>
                <Plus size={16} className="mr-1" /> 新增类目
                    </Button>
            </div>
            <div className="flex flex-wrap gap-2">
              {settings.business.product.customCategories.map((category) => (
                <span
                  key={category}
                  className="inline-flex items-center gap-2 px-3 py-1.5 bg-blue-50 text-blue-600 rounded-xl border border-blue-200"
                >
                  {category}
                  <button type="button" onClick={() => handleCategoryRemove(category)}>
                    <Trash2 size={14} />
                      </button>
                </span>
              ))}
              {!settings.business.product.customCategories.length && (
                <span className="text-xs text-gray-500">暂无自定义类目</span>
                    )}
                  </div>
                </div>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">SKU 生成规则</label>
              <select
                value={settings.business.product.skuGenerationRule}
                onChange={(e) =>
                  setSettings((prev) => ({
                    ...prev,
                    business: {
                      ...prev.business,
                      product: {
                        ...prev.business.product,
                        skuGenerationRule: e.target.value as SystemSettingsType['business']['product']['skuGenerationRule'],
                      },
                    },
                  }))
                }
                className="w-full px-3 py-2 border rounded-xl"
              >
                <option value="color-size">颜色 + 尺寸 组合</option>
                <option value="attribute-combination">按关键属性组合</option>
                <option value="custom">自定义脚本生成</option>
              </select>
              </div>
            <div className="space-y-2">
              <label className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-300">
                <input
                  type="checkbox"
                  checked={settings.business.product.inventoryWarningEnabled}
                  onChange={(e) =>
                    setSettings((prev) => ({
                      ...prev,
                      business: {
                        ...prev.business,
                        product: {
                          ...prev.business.product,
                          inventoryWarningEnabled: e.target.checked,
                        },
                      },
                    }))
                  }
                />
                开启库存预警
              </label>
              <Input
                label="库存告警阈值"
                type="number"
                value={settings.business.product.inventoryWarningThreshold}
                onChange={(e) =>
                  setSettings((prev) => ({
                    ...prev,
                    business: {
                      ...prev.business,
                      product: {
                        ...prev.business.product,
                        inventoryWarningThreshold: Number(e.target.value) || 0,
                      },
                    },
                  }))
                }
              />
            </div>
          </div>
        </div>
      </Card>

      <Card>
        <h3 className="text-base font-semibold flex items-center gap-2 mb-4"><Rocket size={18} /> 营销域</h3>
        <div className="space-y-6">
          <div>
            <div className="flex items-center justify-between mb-3">
              <p className="text-sm font-medium text-gray-700 dark:text-gray-300">会员等级规则</p>
              <Button variant="outline" size="sm" onClick={handleAddMembership}>
                <Plus size={16} className="mr-1" /> 添加等级
              </Button>
            </div>
            <div className="space-y-4">
              {settings.business.marketing.membershipLevels.map((level, index) => (
                <div key={level.id} className="border border-gray-200 dark:border-gray-700 rounded-xl p-4 grid grid-cols-1 md:grid-cols-4 gap-4">
              <Input
                    label="等级名称"
                    value={level.name}
                    onChange={(e) => handleMembershipChange(index, 'name', e.target.value)}
              />
              <Input
                    label="升级门槛（元）"
                    type="number"
                    value={level.threshold}
                    onChange={(e) => handleMembershipChange(index, 'threshold', e.target.value)}
              />
              <Input
                    label="权益说明"
                    value={level.perks}
                    onChange={(e) => handleMembershipChange(index, 'perks', e.target.value)}
                  />
                  <div className="flex items-end">
                    <Button variant="danger" size="sm" onClick={() => handleRemoveMembership(level.id)}>
                      <Trash2 size={16} className="mr-1" /> 删除
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <label className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-300">
              <input
                type="checkbox"
                checked={settings.business.marketing.enableGroupPurchase}
                onChange={(e) =>
                  setSettings((prev) => ({
                    ...prev,
                    business: {
                      ...prev.business,
                      marketing: {
                        ...prev.business.marketing,
                        enableGroupPurchase: e.target.checked,
                      },
                    },
                  }))
                }
              />
              拼团功能（示例：仅对珠宝类目开放）
            </label>
            <label className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-300">
                  <input
                    type="checkbox"
                checked={settings.business.marketing.enablePreSale}
                onChange={(e) =>
                  setSettings((prev) => ({
                    ...prev,
                    business: {
                      ...prev.business,
                      marketing: {
                        ...prev.business.marketing,
                        enablePreSale: e.target.checked,
                      },
                    },
                  }))
                }
              />
              预售功能（可针对 618 等大促快速上线）
                </label>
              </div>

          <div>
            <p className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">营销工具开关与促销模板</p>
            <div className="space-y-2">
              {settings.business.marketing.categoryLimitedTools.map((tool) => (
                <div key={`${tool.category}-${tool.feature}`} className="flex items-center justify-between border border-gray-200 dark:border-gray-700 rounded-xl px-4 py-2">
                  <div>
                    <p className="text-sm font-medium text-gray-700 dark:text-gray-200">{tool.feature} · {tool.category}</p>
                    <p className="text-xs text-gray-500">仅对指定类目开放，避免广泛滥用</p>
            </div>
                  <label className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-300">
                    <input
                      type="checkbox"
                      checked={tool.enabled}
                      onChange={(e) =>
                        setSettings((prev) => ({
                          ...prev,
                          business: {
                            ...prev.business,
                            marketing: {
                              ...prev.business.marketing,
                              categoryLimitedTools: prev.business.marketing.categoryLimitedTools.map((item) =>
                                item === tool ? { ...item, enabled: e.target.checked } : item
                              ),
                            },
                          },
                        }))
                      }
                    />
                    启用
                  </label>
            </div>
              ))}
          </div>
            </div>

            <div>
            <p className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">促销活动参数模板</p>
            <div className="space-y-2">
              {settings.business.marketing.promotionTemplates.map((template) => (
                <div key={template.id} className="border border-dashed border-blue-200 rounded-xl px-4 py-3 text-sm text-blue-600">
                  {template.name}：{template.rule}（{template.scope}）
                </div>
              ))}
            </div>
          </div>
        </div>
      </Card>
    </div>
  )

  const renderPermissionsTab = () => (
    <div className="space-y-6">
      <Card>
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-base font-semibold flex items-center gap-2"><ShieldCheck size={18} /> 角色权限矩阵</h3>
          <label className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-300">
            <input
              type="checkbox"
              checked={settings.permissions.rbacEnabled}
              onChange={(e) =>
                setSettings((prev) => ({
                  ...prev,
                  permissions: {
                    ...prev.permissions,
                    rbacEnabled: e.target.checked,
                  },
                }))
              }
            />
            启用 RBAC 精细化管控
          </label>
        </div>
        <div className="space-y-4">
          {settings.permissions.roles.map((role) => (
            <div key={role.key} className="border border-gray-200 dark:border-gray-700 rounded-xl p-4">
              <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-3">
                <div>
                  <p className="text-sm font-semibold text-gray-700 dark:text-gray-200">{role.name}</p>
                  <p className="text-xs text-gray-500 dark:text-gray-400">{role.description}</p>
                </div>
                {role.restrictedActions?.length ? (
                  <p className="text-xs text-red-500">限制操作：{role.restrictedActions.join(' / ')}</p>
                ) : null}
              </div>
              <div className="mt-3 flex flex-wrap gap-2 text-xs text-gray-600 dark:text-gray-300">
                {['settings:*', 'marketing:*', 'product:view', 'order:view', 'finance:withdrawal', 'merchant:*', 'after-sale:handle'].map((permission) => (
                  <label key={permission} className="inline-flex items-center gap-1 px-3 py-1 rounded-full border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800">
                    <input
                      type="checkbox"
                      checked={role.permissions.includes(permission)}
                      onChange={() => handleRoleToggle(role.key, permission)}
                    />
                    {permission}
                  </label>
                ))}
              </div>
            </div>
          ))}
        </div>
      </Card>

      <Card>
        <h3 className="text-base font-semibold flex items-center gap-2 mb-4"><Store size={18} /> 多店铺/商家适配</h3>
        <div className="space-y-4">
          <label className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-300">
                    <input
                      type="checkbox"
              checked={settings.advanced.multiTenant.enabled}
              onChange={(e) =>
                setSettings((prev) => ({
                  ...prev,
                  advanced: {
                    ...prev.advanced,
                    multiTenant: {
                      ...prev.advanced.multiTenant,
                      enabled: e.target.checked,
                    },
                  },
                }))
              }
            />
            启用多租户／多店铺差异化配置
                  </label>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {settings.advanced.multiTenant.tenantRules.map((rule) => (
              <div key={rule.tenant} className="border border-gray-200 dark:border-gray-700 rounded-xl p-4 text-sm">
                <p className="font-medium text-gray-700 dark:text-gray-200">{rule.tenant}</p>
                <p className="text-xs text-gray-500">启用：{rule.enabledFeatures.join('、') || '—'}</p>
                <p className="text-xs text-gray-500">锁定项目：{rule.lockedSettings.join('、') || '—'}</p>
              </div>
            ))}
          </div>
        </div>
      </Card>
    </div>
  )

  const renderIntegrationsTab = () => (
    <div className="space-y-6">
      <Card>
        <h3 className="text-base font-semibold flex items-center gap-2 mb-4"><Network size={18} /> 第三方登录</h3>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          {(['wechat', 'qq', 'alipay'] as const).map((provider) => {
            const item = settings.integrations.oauthProviders[provider]
            const label = provider === 'wechat' ? '微信' : provider === 'qq' ? 'QQ' : '支付宝'
            return (
              <div key={provider} className="border border-gray-200 dark:border-gray-700 rounded-xl p-4 space-y-3">
                <label className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-300">
                    <input
                      type="checkbox"
                    checked={item.enabled}
                    onChange={(e) =>
                      setSettings((prev) => ({
                        ...prev,
                        integrations: {
                          ...prev.integrations,
                          oauthProviders: {
                            ...prev.integrations.oauthProviders,
                            [provider]: { ...item, enabled: e.target.checked },
                          },
                        },
                      }))
                    }
                  />
                  启用 {label} 登录
                  </label>
                <Input
                  label="AppID"
                  value={item.appId}
                  onChange={(e) => handleOAuthChange(provider, 'appId', e.target.value)}
                />
                <Input
                  label="AppSecret"
                  value={item.appSecret}
                  onChange={(e) => handleOAuthChange(provider, 'appSecret', e.target.value)}
                />
                <Input
                  label="回调地址"
                  value={item.callback}
                  onChange={(e) => handleOAuthChange(provider, 'callback', e.target.value)}
                />
              </div>
            )
          })}
        </div>
      </Card>

      <Card>
        <h3 className="text-base font-semibold flex items-center gap-2 mb-4"><Plug size={18} /> 业务系统对接</h3>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          {(
            [
              { key: 'erp', label: 'ERP（旺店通）' },
              { key: 'wms', label: 'WMS（仓储）' },
              { key: 'crm', label: 'CRM（客户关系）' },
            ] as Array<{ key: 'erp' | 'wms' | 'crm'; label: string }>
          ).map(({ key, label }) => {
            const config = settings.integrations[key]
            return (
              <div key={key} className="border border-gray-200 dark:border-gray-700 rounded-xl p-4 space-y-3 text-sm">
                <label className="flex items-center gap-2 text-gray-600 dark:text-gray-300">
                    <input
                      type="checkbox"
                    checked={config.enabled}
                    onChange={(e) =>
                      setSettings((prev) => ({
                        ...prev,
                        integrations: {
                          ...prev.integrations,
                          [key]: {
                            ...config,
                            enabled: e.target.checked,
                          },
                        },
                      }))
                    }
                  />
                  启用 {label} 对接
                  </label>
                <Input label="Vendor / 渠道" value={config.vendor} onChange={(e) =>
                  setSettings((prev) => ({
                    ...prev,
                    integrations: {
                      ...prev.integrations,
                      [key]: {
                        ...config,
                        vendor: e.target.value,
                      },
                    },
                  }))
                } />
                <Input label="AppKey" value={config.appKey} onChange={(e) =>
                  setSettings((prev) => ({
                    ...prev,
                    integrations: {
                      ...prev.integrations,
                      [key]: {
                        ...config,
                        appKey: e.target.value,
                      },
                    },
                  }))
                } />
                <Input label="AppSecret" value={config.secret} onChange={(e) =>
                  setSettings((prev) => ({
                    ...prev,
                    integrations: {
                      ...prev.integrations,
                      [key]: {
                        ...config,
                        secret: e.target.value,
                      },
                    },
                  }))
                } />
                <Input label="回调地址" value={config.callbackUrl} onChange={(e) =>
                  setSettings((prev) => ({
                    ...prev,
                    integrations: {
                      ...prev.integrations,
                      [key]: {
                        ...config,
                        callbackUrl: e.target.value,
                      },
                    },
                  }))
                } />
                </div>
            )
          })}
              </div>
      </Card>

      <Card>
        <h3 className="text-base font-semibold flex items-center gap-2 mb-4"><Truck size={18} /> 物流接口</h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {settings.integrations.logistics.map((item) => (
            <div key={item.provider} className="border border-gray-200 dark:border-gray-700 rounded-xl p-4 space-y-3 text-sm">
              <label className="flex items-center gap-2 text-gray-600 dark:text-gray-300">
                <input type="checkbox" checked={item.enabled} onChange={() => handleLogisticsToggle(item.provider)} />
                启用 {item.provider}
              </label>
              <Input
                label="API Key"
                value={item.apiKey}
                onChange={(e) =>
                  setSettings((prev) => ({
                    ...prev,
                    integrations: {
                      ...prev.integrations,
                      logistics: prev.integrations.logistics.map((logistic) =>
                        logistic.provider === item.provider ? { ...logistic, apiKey: e.target.value } : logistic
                      ),
                    },
                  }))
                }
              />
              <Input
                label="面单模板"
                value={item.template}
                onChange={(e) =>
                  setSettings((prev) => ({
                    ...prev,
                    integrations: {
                      ...prev.integrations,
                      logistics: prev.integrations.logistics.map((logistic) =>
                        logistic.provider === item.provider ? { ...logistic, template: e.target.value } : logistic
                      ),
                    },
                  }))
                }
              />
            </div>
          ))}
        </div>
      </Card>
    </div>
  )

  const renderTechnicalTab = () => (
    <div className="space-y-6">
      <Card>
        <h3 className="text-base font-semibold flex items-center gap-2 mb-4"><ServerCog size={18} /> 性能与安全</h3>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          <div className="space-y-3 border border-gray-200 dark:border-gray-700 rounded-xl p-4">
            <h4 className="text-sm font-medium text-gray-700 dark:text-gray-200">缓存策略</h4>
            <label className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-300">
              <input
                type="checkbox"
                checked={settings.technical.caching.enabled}
                onChange={(e) =>
                  setSettings((prev) => ({
                    ...prev,
                    technical: {
                      ...prev.technical,
                      caching: {
                        ...prev.technical.caching,
                        enabled: e.target.checked,
                      },
                    },
                  }))
                }
              />
              启用 Redis 缓存
            </label>
                <Input
              label="Redis 过期时间（分钟）"
                  type="number"
              value={settings.technical.caching.redisTtlMinutes}
              onChange={(e) =>
                setSettings((prev) => ({
                  ...prev,
                  technical: {
                    ...prev.technical,
                    caching: {
                      ...prev.technical.caching,
                      redisTtlMinutes: Number(e.target.value) || 0,
                    },
                  },
                }))
              }
            />
            <label className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-300">
              <input
                type="checkbox"
                checked={settings.technical.caching.cacheWarmUp}
                onChange={(e) =>
                  setSettings((prev) => ({
                    ...prev,
                    technical: {
                      ...prev.technical,
                      caching: {
                        ...prev.technical.caching,
                        cacheWarmUp: e.target.checked,
                      },
                    },
                  }))
                }
              />
              大促前自动预热热点接口
            </label>
          </div>

          <div className="space-y-3 border border-gray-200 dark:border-gray-700 rounded-xl p-4">
            <h4 className="text-sm font-medium text-gray-700 dark:text-gray-200">日志保留策略</h4>
                <Input
              label="业务日志保留天数"
                  type="number"
              value={settings.technical.logging.retentionDays}
              onChange={(e) =>
                setSettings((prev) => ({
                  ...prev,
                  technical: {
                    ...prev.technical,
                    logging: {
                      ...prev.technical.logging,
                      retentionDays: Number(e.target.value) || 0,
                    },
                  },
                }))
              }
            />
            <Input
              label="审计日志保留天数"
              type="number"
              value={settings.technical.logging.auditRetentionDays}
              onChange={(e) =>
                setSettings((prev) => ({
                  ...prev,
                  technical: {
                    ...prev.technical,
                    logging: {
                      ...prev.technical.logging,
                      auditRetentionDays: Number(e.target.value) || 0,
                    },
                  },
                }))
              }
            />
            <label className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-300">
                    <input
                      type="checkbox"
                checked={settings.technical.logging.sensitiveDataMasking}
                onChange={(e) =>
                  setSettings((prev) => ({
                    ...prev,
                    technical: {
                      ...prev.technical,
                      logging: {
                        ...prev.technical.logging,
                        sensitiveDataMasking: e.target.checked,
                      },
                    },
                  }))
                }
              />
              开启敏感信息脱敏
                  </label>
                </div>

          <div className="space-y-3 border border-gray-200 dark:border-gray-700 rounded-xl p-4">
            <h4 className="text-sm font-medium text-gray-700 dark:text-gray-200">接口熔断与超时</h4>
              <Input
              label="默认超时（秒）"
              type="number"
              value={settings.technical.api.defaultTimeoutSeconds}
              onChange={(e) =>
                setSettings((prev) => ({
                  ...prev,
                  technical: {
                    ...prev.technical,
                    api: {
                      ...prev.technical.api,
                      defaultTimeoutSeconds: Number(e.target.value) || 0,
                    },
                  },
                }))
              }
              />
              <Input
              label="订单创建接口超时"
                type="number"
              value={settings.technical.api.orderTimeoutSeconds}
              onChange={(e) =>
                setSettings((prev) => ({
                  ...prev,
                  technical: {
                    ...prev.technical,
                    api: {
                      ...prev.technical.api,
                      orderTimeoutSeconds: Number(e.target.value) || 0,
                    },
                  },
                }))
              }
            />
            <label className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-300">
              <input
                type="checkbox"
                checked={settings.technical.api.enableCircuitBreaker}
                onChange={(e) =>
                  setSettings((prev) => ({
                    ...prev,
                    technical: {
                      ...prev.technical,
                      api: {
                        ...prev.technical.api,
                        enableCircuitBreaker: e.target.checked,
                      },
                    },
                  }))
                }
              />
              超时触发熔断保护
            </label>
      </div>
    </div>
      </Card>

      <Card>
        <h3 className="text-base font-semibold flex items-center gap-2 mb-4"><Database size={18} /> 数据保障</h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <label className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-300">
                <input
                  type="checkbox"
              checked={settings.technical.backup.enabled}
              onChange={(e) =>
                setSettings((prev) => ({
                  ...prev,
                  technical: {
                    ...prev.technical,
                    backup: {
                      ...prev.technical.backup,
                      enabled: e.target.checked,
                    },
                  },
                }))
              }
            />
            开启自动备份（每日凌晨2点）
              </label>
          <label className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-300">
            <input
              type="checkbox"
              checked={settings.technical.backup.offsiteEnabled}
              onChange={(e) =>
                setSettings((prev) => ({
                  ...prev,
                  technical: {
                    ...prev.technical,
                    backup: {
                      ...prev.technical.backup,
                      offsiteEnabled: e.target.checked,
                    },
                  },
                }))
              }
            />
            启用异地容灾（数据实时同步备份）
          </label>
          <Input
            label="Cron 表达式"
            value={settings.technical.backup.scheduleCron}
            onChange={(e) =>
              setSettings((prev) => ({
                ...prev,
                technical: {
                  ...prev.technical,
                  backup: {
                    ...prev.technical.backup,
                    scheduleCron: e.target.value,
                  },
                },
              }))
            }
          />
          <Input
            label="最近备份时间"
            value={settings.technical.backup.lastBackupAt || '尚未备份'}
            onChange={(e) =>
              setSettings((prev) => ({
                ...prev,
                technical: {
                  ...prev.technical,
                  backup: {
                    ...prev.technical.backup,
                    lastBackupAt: e.target.value,
                  },
                },
              }))
            }
          />
                  </div>
      </Card>
                </div>
  )

  const renderTab = () => {
    switch (activeTab) {
      case 'branding':
        return renderBrandingTab()
      case 'business':
        return renderBusinessTab()
      case 'permissions':
        return renderPermissionsTab()
      case 'integrations':
        return renderIntegrationsTab()
      case 'technical':
        return renderTechnicalTab()
      default:
        return null
    }
  }

  return (
    <div className="space-y-6 animate-fade-in">
      <div className="space-y-1">
        <h2 className="text-2xl font-bold bg-gradient-to-r from-gray-800 via-gray-700 to-gray-800 dark:from-gray-200 dark:via-gray-300 dark:to-gray-200 bg-clip-text text-transparent">
          {t('settings.title')}
        </h2>
        <p className="text-sm text-gray-500 dark:text-gray-400 max-w-3xl">
          整合平台品牌呈现、业务配置、权限体系与外部系统对接，帮助运营与运维快速掌控核心参数。
        </p>
      </div>

      <Card className="dark:bg-gray-800 dark:border-gray-700">
        <div className="flex flex-wrap gap-2 -mx-6 -mt-6 px-6 pt-6 mb-6 border-b border-gray-200 dark:border-gray-700">
          {tabs.map((tab) => {
            const Icon = tab.icon
            const active = activeTab === tab.id
            return (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`flex items-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all ${
                  active
                    ? 'bg-gradient-to-r from-blue-500 to-blue-600 text-white shadow-md'
                    : 'text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700'
                }`}
              >
                <Icon size={18} />
                {tab.label}
              </button>
            )
          })}
        </div>

        <div className="space-y-6">
          {renderTab()}
        </div>

        <div className="flex justify-between items-center pt-6 border-t border-gray-200 dark:border-gray-700 mt-6">
          {saveSuccess && (
            <div className="flex items-center gap-2 text-green-600 dark:text-green-400 text-sm">
              <CheckCircle size={18} />
              <span>保存成功，版本已自动归档</span>
            </div>
          )}
          <div className="flex gap-3 ml-auto">
            <Button variant="outline" onClick={handleReset}>
              <RefreshCw size={18} className="mr-2" />
              {t('common.reset')}
            </Button>
            <Button onClick={handleSave} loading={loading}>
              <Save size={18} className="mr-2" />
              {t('common.save')}
            </Button>
          </div>
        </div>
      </Card>
    </div>
  )
}

export default SystemSettings
